
/**
 * 上传按钮美化
 */
$('.J_filebox').on('click', '.daui-filebox__control', function(){
	$(this).parent().prev('.daui-filebox__file').click();
})
$('.J_filebox').on('change', "input[type='file']", function(){
	console.log('input,file,change');
	var parentObj = $(this).parent();
    var filePath = $(this).val();
    var arr = filePath.split('\\');
    var fileName = arr[arr.length-1];
    parentObj.find('.daui-filebox__name').html(fileName);
    var objUrl = getFileObjectURL(this.files[0]);
    if (objUrl) {
        parentObj.find('.daui-filebox__bd>img').attr("src", objUrl);
        parentObj.find('.daui-filebox__bd>img').fadeIn();
    }
});
/**
 * 建立一個可存取到該file的url
 * PS: 瀏覽器必須支援HTML5 File API
 */
function getFileObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file);
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file);
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file);
    }
    return url;
}

/*复选框全选(支持多个，纵横双控全选)。
 *实例：版块编辑-权限相关（双控），验证机制-验证策略（单控）
 *说明：
 *	"J_check"的"data-xid"对应其左侧"J_check_all"的"data-checklist"；
 *	"J_check"的"data-yid"对应其上方"J_check_all"的"data-checklist"；
 *	全选框的"data-direction"代表其控制的全选方向(x或y)；
 *	"J_check_wrap"同一块全选操作区域的父标签class，多个调用考虑
 */

if($('.J_check_wrap').length){
    var total_check_all = $('input.J_check_all');

    //遍历所有全选框
    $.each(total_check_all, function(){
        var check_all = $(this),
            check_items;

        //分组各纵横项
        var check_all_direction = check_all.data('direction');
        check_items = $('input.J_check[data-' + check_all_direction + 'id="' + check_all.data('checklist') + '"]');
        
        //点击全选框
        check_all.change(function(e){
            var check_wrap = check_all.parents('.J_check_wrap'); //当前操作区域所有复选框的父标签（重用考虑）

            if ($(this).prop('checked')) {
                //全选状态
                check_items.prop('checked', true);

                //所有项都被选中
                if (check_wrap.find('input.J_check').length === check_wrap.find('input.J_check:checked').length) {
                    check_wrap.find(total_check_all).prop('checked', true);
                }

            } else {
                //非全选状态
                check_items.prop('checked', false);

                //另一方向的全选框取消全选状态
                var direction_invert = check_all_direction === 'x' ? 'y' : 'x';
                check_wrap.find($('input.J_check_all[data-direction="' + direction_invert + '"]')).prop('checked', false);
            }
        });

        //点击非全选时判断是否全部勾选
        check_items.change(function () {
            if ($(this).prop('checked')) {
                if (check_items.filter(':checked').length === check_items.length) {
                    //已选择和未选择的复选框数相等
                    check_all.prop('checked', true);
                }
            } else {
                check_all.prop('checked', false);
            }
        });
    });
}

//批量提交并提示
var layerConfirm_list = $('button.J_layerConfirmSubmit');
if (layerConfirm_list.length) {
	$('.J_layerConfirmSubmit').on('click', function(e){
		e.preventDefault();
		var btn = $(this),
			form = btn.parents('form.J_ajaxForm');
		
		var beforetip = $(this).data('beforetip');
		var isloadding = $(this).data('isloadding');
		var submitdisabled = $(this).data('submitdisabled');
		var tip = $(this).data('tip');

		layer.confirm(tip, {
			btn: ['确定','取消'], //按钮
			shade: false //不显示遮罩
		}, function(){
			form.ajaxSubmit({
				url: btn.data('action') ? btn.data('action') : form.attr('action'), //按钮上是否自定义提交地址(多按钮情况)
				dataType: 'json',
				contentType: "application/x-www-form-urlencoded;charset=utf-8",
				beforeSubmit: function (arr, $form, options){
					var text = btn.text();

					if(beforetip){
						layer.msg(beforetip, {icon: 16});
					}
					if(submitdisabled == 1){
						btn.prop('disabled', true);
					}
					if(typeof isloadding != "undefined"){
						if(isloadding == 1){
							layer.load(0, {
								shade: [0.1,'#fff'],
								time: 1000
							});
						}
						if(isloadding == 2){
							layer.msg('提交中', {
								icon: 16,
								shade: 0.01
							});
						}
					}
				},
				success: function (ret, statusText, xhr, $form){
					var text = btn.text();
					//按钮文案、状态修改
					//btn.removeClass('disabled').text(text.replace('中...', '')).parent().find('span').remove();
					//btn.text(text.replace('中...', ''))
					//btn.removeClass('disabled').text(text.replace('中...', ''));
					if(ret.code == 1){
						Wei.Util.wapTipNew({msg: ret.msg, icon: 1, data: ret.data, url: ret.url});
					}else if(ret.code == 0){
						Wei.Util.wapTipNew({msg: ret.msg, icon: 2, data: ret.data, url: ret.url});
						btn.prop('disabled', false);
					}else if(ret.code == 'layerConfirm'){
						var extra = ret.extra;
						layer.confirm(ret.msg, {
							btn: [extra.okName, extra.cancelName], //按钮
							shade: false //不显示遮罩
						}, function(){
							if (extra.okUrl){
								window.location.href = extra.okUrl;
							};
						}, function(){
						});
					}

					Wei.Util.readyToJump(ret);

					try {
						var re = afterSubmit();
						if(re != true){
							return;
						};
					} catch (err) {

					}
				},
				error: function (ret, statusText, xhr, $form){
					//alert('error');
				}
			});
		}, function(){
		});
	});
}

$(document).on('click', '.J_layerPcDialogForDialog', function(e){
	console.log('J_layerPcDialogForDialog')
	e.preventDefault();
    var btn = $(this),
        form = btn.parents('form');
	var url = $(this).data('action');
	var title = $(this).data('tip');
    form.ajaxSubmit({
        url: btn.data('action') ? btn.data('action') : form.attr('action'),
        dataType: 'json',
        contentType: "application/x-www-form-urlencoded;charset=utf-8",
        beforeSubmit: function (arr, $form, options){
        },
        success: function (ret, status, xhr){
            if(ret.code == 1){
	            var data = ret.data;
				var html = data.html;
				layer.closeAll();
				layer.open({
					shade: false,
					type: 1,
					closeBtn: 1, //不显示关闭按钮
					shift: 2,
					maxWidth: 640,
					title: title,
					content: html
				});
            }else if(ret.code == 0){
				Wei.Util.wapTipNew({msg: ret.msg, icon: 2, data: ret.data, url: ret.url});
            }
        },
    });
});

$(document).on('click', '.J_layerConfirmForDialog', function(e){
	e.preventDefault();
	var obj = $(this);
	var url = $(this).attr('href');
	var tip = $(this).data('tip');
	var jump = $(this).data('jump');
	var param = {jump : jump};

	layer.confirm(tip, {
		btn: ['确定','取消'], //按钮
		shade: false //不显示遮罩
	}, function(){
		var index = layer.load(1, {
			shade: [0.1,'#fff'],
			time: 1000
		});
		$.get(url, param, function(ret){
			if(ret.code == 1){
				var data = ret.data;
				Wei.Util.wapTipNew({msg: ret.msg, icon: 1, time: ret.time, mode: data.mode}, function(){
					layer.closeAll();
					Wei.Util.readyToJump(ret);
				});
			}else if(ret.code == 0){
				var data = ret.data;
				Wei.Util.wapTipNew({msg: ret.msg, icon: 2, time: ret.time, mode: data.mode}, function(){
					layer.closeAll();
					Wei.Util.readyToJump(ret);
				});
			}
			try {
				var re = afterConfirm(obj);
				if (re != true) {
					return;
				};
			} catch (err) {

			}
		}, 'json');
	}, function(){
	});
});